//
//  SocketEngineWebsocket.swift
//  QHSocketIODemo
//
//  Created by Anakin chen on 2017/5/21.
//  Copyright © 2017年 chen. All rights reserved.
//

import Foundation

public protocol SocketEngineWebsocket: SocketEngineSpec, WebSocketDelegate {
    func sendWebSocketMessage(_ str: String, withType type: SocketEnginePacketType, withData datas: [Data])
}

extension SocketEngineWebsocket {
    func probeWebSocket() {
        if ws?.isConnected ?? false {
            sendWebSocketMessage("probe", withType: .ping, withData: [])
        }
    }
    
    public func sendWebSocketMessage(_ str: String, withType type: SocketEnginePacketType, withData datas: [Data]) {
        DefaultSocketLogger.Logger.log("Sending ws: %@ as type: %@", type: "SocketEngine", args: str, type.rawValue)
        
        ws?.write(string: "\(type.rawValue)\(str)")
        
        for data in datas {
            if case let .left(bin) = createBinaryDataForSend(using: data) {
                ws?.write(data: bin)
            }
        }
    }
    
    public func websocketDidReceiveMessage(socket: WebSocket, text: String) {
        parseEngineMessage(text, fromPolling: false)
    }
    
    public func websocketDidReceiveData(socket: WebSocket, data: Data) {
        parseEngineData(data)
    }
    
}
